package cn.edu.zjicm.wordsnet_d.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.searchDate;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.fragment.WordDetailFragment;
import cn.edu.zjicm.wordsnet_d.util.TypefaceUtil;

import com.umeng.analytics.MobclickAgent;

public class SearchActivity extends WordBaseActivity implements OnClickListener {
	public static void startActivity(Context context) {
		Intent i = new Intent(context, SearchActivity.class);
		context.startActivity(i);
	}

	private ViewFlipper mainFlipper;
	private ListView listView;
	private WordDetailFragment mDetailFragment;

	private WordFactory wf;
	private InputMethodManager imm;
	private OneWord word = null;
	private List<HashMap<String, Object>> data;
	private boolean toSearch = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		wf = WordFactory.getInstance(this);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);// 获得软键盘的对象

		// 设定调整音量为媒体音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		initTitle();

		setContentView(R.layout.activity_search);
		findViews();
		initViews();

		mDetailFragment = new WordDetailFragment(null);
		mDetailFragment.setForSearchView(true);
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.add(R.id.word_detail_fragment_container, mDetailFragment);
		ft.commit();
	}

	void initTitle() {
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		showSearchView(mTextWatcher, this, enterKeyToSearch);
		changeBackground();
		// searchEditText.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);
		imm.showSoftInput(searchEditText, 0); // 显示键盘
	}

	private void findViews() {
		mainFlipper = (ViewFlipper) findViewById(R.id.search_main_flipper);// 显示搜索到的单词的界面
		listView = (ListView) findViewById(R.id.listView_search);// 显示搜索到的单词的界面
	}

	public void initViews() {
		listView.setOnItemClickListener(listViewItemClickListener);
	}

	private void showWordsSearched() {// 显示listView中搜索到的内容conqueror() {
		mainFlipper.setDisplayedChild(0);
		if (searchEditText.getText().toString().length() == 0) {
			listView.setAdapter(null);
			return;
		}

		List<searchDate> searchs = wf.getSearchData(searchEditText.getText().toString());

		data = new ArrayList<HashMap<String, Object>>();
		for (searchDate search : searchs) {
			HashMap<String, Object> item = new HashMap<String, Object>();
			item.put("lemma", search.getLemma());
			item.put("senses", search.getSenses());
			item.put("phonetic", search.getPhonetic());
			data.add(item);
		}

		// SimpleAdapter adapter = new SimpleAdapter(this, data,
		// R.layout.search_detail, new String[] { "lemma", "phonetic", "senses"
		// }, new int[] { R.id.word_note_item_word, R.id.word_note_item_phe,
		// R.id.word_note_item_translation });

		BaseAdapter mBaseAdapter = new BaseAdapter() {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = View.inflate(SearchActivity.this, R.layout.search_detail, null);
				TextView lemma = (TextView) view.findViewById(R.id.word_note_item_word);
				TextView phonetic = (TextView) view.findViewById(R.id.word_note_item_phe);
				TextView senses = (TextView) view.findViewById(R.id.word_note_item_translation);
				TypefaceUtil.getInstance(SearchActivity.this).setTypeface(phonetic);
				lemma.setText(data.get(position).get("lemma") + "");
				phonetic.setText(data.get(position).get("phonetic") + "");
				senses.setText(data.get(position).get("senses") + "");
				return view;
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public int getCount() {
				return data.size();
			}
		};

		// SimpleAdapter adapter = new SimpleAdapter(this, data,
		// R.layout.view_word_note_item, new String[] { "lemma",
		// "phonetic", "senses" }, new int[] {
		// R.id.word_note_item_word, R.id.word_note_item_phe,
		// R.id.word_note_item_translation });

		// SimpleAdapter adapter = new SimpleAdapter(this, data,
		// R.layout.search_detail,
		// new String[]{"lemma", "senses"}, new int[]{R.id.search_lemma,
		// R.id.search_senses});

		// listView.setAdapter(adapter);
		listView.setAdapter(mBaseAdapter);
	}

	private void showParaphrase(String lemma) {
		word = wf.getOneWordByLemma(lemma);
		// Log.e("book", word.getBook_id() + "");
		imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);// 点击按钮后将输入法自动隐藏掉
		if (word == null) {// 数据库中没有相应要查询的单词
			mainFlipper.setDisplayedChild(2);
		} else {
			// 当数据库中存在要查询的单词执行下面语句
			mDetailFragment.initViewForNewWord(word);
			mDetailFragment.showAddButton();
			mainFlipper.setDisplayedChild(1);
		}
	}

	@Override
	public void onClick(View view) {
		if (view == searchClearButton) {
			super.setSearchTextEmpty(true);
			showWordsSearched();
			imm.showSoftInput(searchEditText, 0); // 显示键盘
		} else if (view == searchEditText) {
			if (!toSearch) {
				showWordsSearched();
				mainFlipper.setDisplayedChild(0);
				if (isSearchTextEmpty()) {
					searchEditText.setSelection(0);// 设置光标位置
				}
			} else
				toSearch = false;
		}
	}

	TextWatcher mTextWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			setSearchTextEmpty(searchEditText.getText().toString().length() == 0);
			String str = searchEditText.getText().toString();
			int strLength = str.length();
			if (strLength > 0) {
				showWordsSearched();
			}
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};

	OnEditorActionListener enterKeyToSearch = new OnEditorActionListener() {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_SEARCH) {
				showParaphrase(searchEditText.getText().toString());
				toSearch = true;
			}
			return false;
		}
	};

	OnItemClickListener listViewItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			final TextView tv = (TextView) view.findViewById(R.id.word_note_item_word);
			searchEditText.removeTextChangedListener(mTextWatcher);
			searchEditText.setText("");
			searchEditText.append(tv.getText().toString());
			searchEditText.addTextChangedListener(mTextWatcher);
			showParaphrase(tv.getText().toString());
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
